<?php

class Empeval_AuthData_AD implements Empeval_AuthData_ILoginData {
	
	private $login;
	private $password;
	private $_identity = null;
	
	public function __construct($login, $password) {
		$this->login = $login;
		$this->password = $password;
	}
	
	public function getUser() {
		$auth = Zend_Auth::getInstance();
		$adapter = new Zend_Auth_Adapter_Ldap($this->_getOptions(), $this->login, $this->password);
		$result = $auth->authenticate($adapter);
		
		if ($result->isValid()) {
			$this->_identity = $result->getIdentity();
			return EmpevalUsersQuery::create()
				->withRoles()
				->withPosition()
				->filterByAd($this->_identity)
				->filterByActive(true)
				->filterByDeleted(null, Criteria::ISNULL)
				->find()
				->getFirst();
		}
		return null;
	}
	
	public function getId() {
		return $this->_identity;
	}
	
	private function _getOptions() {
		$out = array();
		foreach (Empeval_Config::getInstance()->ldap->server as $server) {
			if (!(bool)$server->enable)
				continue;
			$out[] = $server->options->toArray();
		}
		return $out;
	}
	
}